import { createClient } from '@supabase/supabase-js';
import { saveCode } from '../lib/codeStorage';
import { config } from '../config';
import { workflowService } from './workflow.service';
import { scheduleService } from './schedule.service';

const supabaseUrl = config.supabaseUrl;
const supabaseKey = config.supabaseKey;
// console.log(import.meta.env.VITE_SUPABASE_URL)
if (!supabaseUrl || !supabaseKey) {
  throw new Error('缺少环境变量配置');
}

const supabase = createClient(supabaseUrl, supabaseKey);

// 基础请求方法
const baseRequest = async (url: string, method: string, body?: any) => {
  try {
    const response = await fetch(`http://127.0.0.1:4523/m1/5819718-5505036-default${url}`, {
      method,
      headers: {
        'Content-Type': 'application/json',
      },
      body: body ? JSON.stringify(body) : undefined,
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || '请求失败');
    }
    
    return await response.json();
  } catch (error) {
    throw error instanceof Error ? error : new Error('网络请求异常');
  }
};

// 公共API
export const commonAPI = {
  fetchTools: () => baseRequest('/api/code-list', 'POST')
};

// 导出工作流服务和定时任务服务
export { workflowService, scheduleService };
